<template>
  <div class="users">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主体区域 -->
    <el-card class="mt16">
      <!-- 搜索框 -->
      <el-row>
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @input="searchCon"
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUsers">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户表格 -->
      <el-table :data="users" border style="width: 100%" class="mt16">
        <el-table-column type="index" label="#" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="120">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="120">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="120">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="200">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="120">
          <template slot-scope="scope">
            <div>
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeSwitch(scope.row)"
              >
              </el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              @click="edit(scope.row)"
              type="primary"
              icon="el-icon-edit"
              size="small"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="del(scope.row.id)"
            ></el-button>
            <!-- 设置 -->
            <el-button
              type="warning"
              size="small"
              icon="el-icon-setting"
              @click="DisRoles(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <!-- 1.size-change:pageSize(每页条数) 改变时会触发 -->
      <!-- 2.current-change:currentPage(当前页码) 改变时会触发 -->
      <!-- 3.page-sizes:每页显示个数选择器的选项设置 -->
      <!-- 4.page-size每页显示条目个数，支持 .sync 修饰符 -->
      <!-- 5.layout:控制分页器布局 -->
      <!-- 6.total分页总条目数 -->
      <!-- 7.current-page:当前页码数 -->
      <el-pagination
        class="mt16"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form ref="addUserRef" :model="addUserData" :rules="addUserRules">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="addUserData.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addUserData.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserData.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserData.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserOk">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogEdit">
      <el-form ref="editRef" :model="addUserData" :rules="addUserRules">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="addUserData.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserData.email" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserData.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEdit = false">取 消</el-button>
        <el-button type="primary" @click="editOk">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="dialogDisRoles" width="30%">
      <div>
        <p>当前用户:{{ this.DisRolesData.username }}</p>
        <p>当前角色:{{ this.DisRolesData.role_name }}</p>
        <!-- 下拉框 -->
        <el-select v-model="rolesId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDisRoles = false">取 消</el-button>
        <el-button type="primary" @click="DisRolesOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsersList,
  getNewUsers,
  getChangeSwitch,
  editChange,
  deleteUsers,
  getRolesList,
  setRole
} from '@/http/api'
import _ from 'lodash'
export default {
  name: 'users',
  components: {},
  data() {
    // 编写邮箱验证规则
    const checkEmail = (rule, value, callback) => {
      // 邮箱正则
      const reg =
        /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      // 如果不满足规则报错提示
      if (!reg.test(value)) {
        // 报错提示
        return callback(new Error('您的邮箱格式不正确，请重新输入'))
      }
      // 满足规则放行
      callback()
    }

    // 编写电话验证规则
    const checkMobile = (rule, value, callback) => {
      const reg = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/
      // 如果不满足规则报错提示
      if (!reg.test(value)) {
        // 报错提示
        return callback(new Error('您的电话格式不正确，请重新输入'))
      }
      // 满足规则放行
      callback()
    }
    return {
      rolesId: {},
      rolesList: {}, //角色列表数据
      DisRolesData: {}, //当前用户信息
      addUserData: {},
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }, //判断是否为空
          { min: 5, max: 10, message: '用户名要在5到10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }, //判断是否为空
          { min: 5, max: 10, message: '密码要在5到10个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }, //判断是否为空
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }, //判断是否为空
          { validator: checkMobile, trigger: 'blur' }
        ]
      }, //添加用户表单验证规则
      tableData: [],
      // 调用接口传参
      queryInfo: {
        query: '', //搜索关键字
        pagenum: 1, //当前页码
        pagesize: 5 //每页显示条数
      },
      total: 0, // 用户总数
      users: [], //用户列表数组
      dialogFormVisible: false, //显示隐藏对话框
      dialogEdit: false, //显示隐藏编辑对话框
      dialogDisRoles: false //显示隐藏分配角色对话框
      // editList: {} //存储编辑用户数据
    }
  },
  created() {
    this.getUsersList()
  },
  mounted() {},
  methods: {
    // 分配角色
    DisRoles(row) {
      // 显示隐藏框
      this.dialogDisRoles = true
      const { id, username, role_name } = row
      this.DisRolesData = { id, username, role_name }
      // 获取角色列表数据
      getRolesList().then((res) => {
        console.log(res)
        this.rolesList = res
      })
    },
    // 分配角色完成
    DisRolesOk() {
      setRole(this.DisRolesData.id, this.rolesId).then((res) => {
        // 刷新用户列表
        this.getUsersList()
      })
      this.dialogDisRoles = false
    },
    // 删除用户
    del(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        // 确定删除 调用接口
        .then(() => {
          deleteUsers(id).then(() => {
            // 提示
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 更新列表
            this.getUsersList()
          })
        })
        // 取消删除
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取用户列表数据
    async getUsersList() {
      const res = await getUsersList(this.queryInfo)
      console.log(res)
      const { users, total } = res
      this.total = total
      this.users = users
    },
    // 每页条数 改变时会触发
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryInfo.pagesize = val
      this.getUsersList()
    },
    // 当前页码 改变时会触发
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      this.getUsersList()
    },
    // 搜索功能的防抖
    searchCon: _.debounce(function () {
      this.getUsersList()
    }, 300),
    // 添加用户
    addUsers() {
      this.dialogFormVisible = true
    },
    // 确定向后台添加新用户
    addUserOk() {
      // 验证输入是否合法
      this.$refs.addUserRef.validate(async (valid) => {
        if (!valid) return false
        // 否则调用后台接口添加新用户
        const res = await getNewUsers(this.addUserData)
        console.log(res)
        // 隐藏对话框
        this.dialogFormVisible = false
        // 刷新用户列表
        this.getUsersList()
      })
    },
    // 改变用户状态
    async changeSwitch(row) {
      console.log(row)
      // 解构需要传参的数据
      const { id, mg_state } = row
      await getChangeSwitch(id, mg_state)
      this.getUsersList() //更新用户列表
    },
    // 编辑用户
    edit(row) {
      console.log(row)
      // 回填数据
      this.addUserData = row
      // 显示对话框
      this.dialogEdit = true
    },
    // 编辑完成
    editOk() {
      // 验证输入是否合法
      this.$refs.editRef.validate(async (valid) => {
        if (!valid) return false
        // 解构赋值 获取需要传参的数据
        const { id, email, mobile } = this.addUserData
        // 否则调用后台接口更新数据
        const res = await editChange(id, { email, mobile })
        console.log(res)
        // 隐藏对话框
        this.dialogEdit = false
        // 清空数据
        this.addUserData = {}
        // 刷新用户列表
        this.getUsersList()
      })
    }
  }
}
</script>
<style scoped lang="scss">
.users {
  margin: 0;
  padding: 0;
}
.mt16 {
  margin-top: 16px;
}
</style>
